package com.darren.euc.action;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.darren.euc.entity.ResponseJSON;
import com.darren.euc.entity.Room;
import com.darren.euc.service.RoomService;
import com.darren.euc.util.PropertyHelper;
import com.darren.euc.util.StringUtil;
import com.darren.euc.util.light.LightUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
@RequestMapping("/light")
public class LightAction {

	private static final Logger log = Logger.getLogger(LightAction.class);
	
	@Autowired
    private RoomService roomService;
	
	@ResponseBody
    @RequestMapping(value = "/rooms",method = RequestMethod.POST)
    public ResponseJSON getAllRoomByMemberId(@RequestBody JSONObject requestJson,HttpServletRequest request,HttpServletResponse response) { 
    	ResponseJSON responseJson = new ResponseJSON();
    	Integer memberId = requestJson.getInt("memberId");
    	List<Room> rooms = roomService.findRooByMemberId(memberId);
    	if(rooms != null && rooms.size() > 0){
    		for(Room room:rooms){
    			room.setCity(null);
    			room.setProvince(null);
    			room.setCreateUser(null);
    			room.setLastModifyUser(null);
    			room.setSpace(null);
        		if(!StringUtil.isEmptyOrWhitespace(room.getFriend()) && !StringUtil.isEmptyOrWhitespace(room.getLightNames())){
        			try {
        	    		String jsonString = LightUtils.getGateWayDeviceList(room.getFriend(),PropertyHelper.getLightPhone(),PropertyHelper.getLightPassword());
        	    		JSONObject deviceJson = JSONObject.fromObject(jsonString);    		
        	    		JSONArray jsonArray = deviceJson.getJSONArray("devices");
        	    		JSONArray lightArray = new JSONArray(); 
        	    		String[] lights = room.getLightNames().split(";");
        				if (jsonArray.size() > 0) {
        					for (int i = 0; i < jsonArray.size(); i++) {//循环所有设备
        						JSONObject device = jsonArray.getJSONObject(i);
        						if ("light".equals(device.getString("dev_class_type")) || "dimmer".equals(device.getString("dev_class_type"))){ //只取灯设备
        							if( room.getRoomName().equals(device.getString("room_name"))) {//只取当前房间的灯							
        								for(String light:lights){
        									if(light.trim().equals(device.getString("device_name"))){//取房间信息表里添加的灯，未添加的不取
        										device.put("roomId", room.getId());
        										lightArray.add(device);
//        										room.getLights().add(device);
        									}
        								}
        							}
        						}
        					}
        				} 
        				room.setLights(lightArray);
        			} catch (Exception e) {
        				log.error(e.getMessage(),e);
        			}
        		}
        	}
    		responseJson.setStatus(0);
    		responseJson.setMessage("获取成功！");
    	}else{
    		responseJson.setStatus(-1);
    		responseJson.setMessage("未找到该会员匹配的房间！");
    	}    	
    	responseJson.setData(rooms);    	
        return responseJson;
    }
	
	
	@ResponseBody
    @RequestMapping(value = "/devices",method = RequestMethod.POST)
    public ResponseJSON getAllLightByRoomId(@RequestBody JSONObject requestJson,HttpServletRequest request,HttpServletResponse response) { 
    	ResponseJSON responseJson = new ResponseJSON();
    	Integer roomId = requestJson.getInt("roomId");
    	Room room = roomService.findRooById(roomId);
    	if(room == null){
    		responseJson.setStatus(-1);
    		responseJson.setMessage("未找到指定的房间！");
    		return responseJson;
    	}else if(StringUtil.isEmptyOrWhitespace(room.getFriend())){
    		responseJson.setStatus(-2);
    		responseJson.setMessage("该房间未添加灯网关！");
    		return responseJson;
    	}else if(StringUtil.isEmptyOrWhitespace(room.getLightNames())){
    		responseJson.setStatus(-3);
    		responseJson.setMessage("该房间未添加灯！");
    		return responseJson;
    	}
    	try {
    		String jsonString = LightUtils.getGateWayDeviceList(room.getFriend(),PropertyHelper.getLightPhone(),PropertyHelper.getLightPassword());
    		JSONObject deviceJson = JSONObject.fromObject(jsonString);    		
    		JSONArray jsonArray = deviceJson.getJSONArray("devices");
    		JSONArray deviceArray = new JSONArray();
    		String[] lights = room.getLightNames().split(";");
			if (jsonArray.size() > 0) {
				for (int i = 0; i < jsonArray.size(); i++) {//循环所有设备
					JSONObject device = jsonArray.getJSONObject(i);
					if ("light".equals(device.getString("dev_class_type")) || "dimmer".equals(device.getString("dev_class_type"))){ //只取灯设备
						if( room.getRoomName().equals(device.getString("room_name"))) {//只取当前房间的灯							
							for(String light:lights){
								if(light.trim().equals(device.getString("device_name"))){//取房间信息表里添加的灯，未添加的不取
									device.put("roomId", roomId);
									deviceArray.add(device);
								}
							}
						}
					}
				}
			} 		
    		responseJson.setData(deviceArray);
    		responseJson.setStatus(0);
    		responseJson.setMessage("获取成功！");
    		return responseJson;
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
    	responseJson.setStatus(-6);
		responseJson.setMessage("获取失败！");
        return responseJson;
    }
	
	
	@ResponseBody
    @RequestMapping(value = "/control",method = RequestMethod.POST)
    public ResponseJSON setLightOnOrOff(@RequestBody JSONObject requestJson,HttpServletRequest request,HttpServletResponse response) throws Exception { 
    	ResponseJSON responseJson = new ResponseJSON();
    	Integer roomId = requestJson.getInt("roomId");
    	Room room = roomService.findRooById(roomId);
    	if(room == null){
    		responseJson.setStatus(-1);
    		responseJson.setMessage("未找到指定的房间！");
    		return responseJson;
    	}else if(StringUtil.isEmptyOrWhitespace(room.getFriend())){
    		responseJson.setStatus(-2);
    		responseJson.setMessage("该房间未添加灯网关！");
    		return responseJson;
    	}else if(StringUtil.isEmptyOrWhitespace(room.getLightNames())){
    		responseJson.setStatus(-3);
    		responseJson.setMessage("该房间未添加灯！");
    		return responseJson;
    	}
    	try {
    		String device_name = requestJson.getString("device_name");
    		String room_name = requestJson.getString("room_name");
    		String on_off = requestJson.getString("on_off");
    		boolean controlResult = LightUtils.controlLight(room.getFriend(), device_name, room_name, PropertyHelper.getLightPhone(),PropertyHelper.getLightPassword(), on_off);
    		if(controlResult == true){
    			responseJson.setStatus(0);
        		responseJson.setMessage("操作成功！");
    		}else{
    			responseJson.setStatus(-5);
        		responseJson.setMessage("操作失败！");
    		}
    		return responseJson;
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
    	responseJson.setStatus(-10);
		responseJson.setMessage("操作失败！");
        return responseJson;
    }
	
	
}